$(function () {
    layui.use('layer', function(){
        layer = (parent.layer === undefined) ? layui.layer : parent.layer;
    });
    var topicGroupId = sessionStorage.getItem('topicGroupId');
    $("#TopicManageDetail").attr("topicGroupId", topicGroupId);
    getGroupAll(topicGroupId);

    /**点击加题进行跳转**/
    $(document).on('click', ".addTopic", function (){
        var topicGroupIdName="添加题目到topicGroupId="+topicGroupId;
        openUrl(window.location.href,"AddTopic.html",topicGroupIdName);
        //对面包屑进行编辑
        var html='<a data-href="AddTopic.html">添加题目</a>';
        $(parent.document).find(".layui-breadcrumb a:last-child").append('<span class="layui-box">&gt;</span>');
        $(parent.document).find(".layui-breadcrumb").append(html);

        sessionStorage.setItem('topicGroupIdTo',topicGroupId);
        sessionStorage.setItem('topicGroupIdName',topicGroupIdName);
    });

    /**题目详情页展示收缩**/
    $(document).on('click', ".TitleDetail_title", function () {
        $(this).next().toggle();
    });

    /**题目详情页排序可拖拽**/
    $("#topicSort")[0].onclick = function () {
        $("#TopicManageDetail_popup .popup_body .TitleDetailAll .TitleDetail_content").css("display", "none");
        $(this).next().css("display", "inline-block");
        $(this).next().next().css("display", "inline-block");
        $(this).css("display", "none");
        $(this).prev().css("display", "none");
        $(".addTopic").css("display","none");
        $("#TopicManageDetail_popup .popup_title span").css("display", "none");
        window.x = new Sortable(TitleDetailAll, {
            group: "words",
            store: {
                get: function (sortable) {
                    var order = localStorage.getItem(sortable.options.group);
                    return order ? order.split('|') : [];
                },
                set: function (sortable) {
                    var order = sortable.toArray();
                    order = [];
                    localStorage.setItem(sortable.options.group, order.join('|'));
                }
            },
            onEnd: function () {
                var spanArr = $("#TitleDetailAll>li>.TitleDetail>.TitleDetail_title>.TitleNo span");
                for (var i = 0; i < spanArr.length; i++) {
                    spanArr[i].innerHTML = i + 1;
                }
            }
        });
    };
    /**题目详情页排序可保存**/
    $("#topicSortSave")[0].onclick = function () {
        $(this).css("display", "none");
        $(this).next().css("display", "none");
        $(this).prev().css("display", "inline-block");
        $(this).prev().prev().css("display", "inline-block");
        $("#TopicManageDetail_popup .popup_title span").css("display", "inline-block");
        $("#TopicManageDetail_popup .popup_body .TitleDetailAll .TitleDetail_content").css("display", "block");
        topicIdListSort();
    };

    /**点击添加阅读题子项**/
    $(document).on('click', "#TitleDetailAll .TitleDetail_title .addReadingItem", function (event) {
        event.stopPropagation();
        sessionStorage.setItem('topicReadingId',$(this).parent().parent().parent().attr("topicid"));
        openUrl(window.location.href,"AddReadingTopic.html","添加小题");
    });
    /**题目详情删除一行**/
    $(document).on('click', "#TitleDetailAll .TitleDetail_title .topicRevocation", function (event) {
        event.stopPropagation();
        var topicId = $(this).parent().parent().parent();
        var groupId=topicId.parent();
        var topicGroupRevocation = {
            "topicId": topicId.attr("topicid"),
            "groupId": groupId.attr("groupid"),
            "token": User.token
        };
        topicGroupRevocation = JSON.stringify(topicGroupRevocation);
        layer.confirm('是否删除', {
            btn: ['确定','取消'] //按钮
        }, function(index, layero){
            $.ajax({
                type: 'POST',  //POST/PUT/DELETE/HEAD
                url: Doman.url + Doman.topicGroupRevocation,
                contentType: "application/json",
                data: topicGroupRevocation,
                success: function (data) {
                    // var topicDetailName=sessionStorage.getItem("topicDetailName");
                    // var arr=topicDetailName.split("-");
                    if($(".TitleDetailAll").attr("count")-1>0){
                        // var topicDetaiPrelName=arr[0]+"-"+(parseInt(arr[1])-1)+"题";
                        // sessionStorage.setItem('topicDetailName',topicDetaiPrelName);
                        // openUrl(window.location.href,"topicList.html","题目列表");
                        openUrl(window.location.href,"TopicManageDetail.html");
                        // window.top.xhTop.closeTabByName(topicDetailName);
                    }else{
                        openUrl(window.location.href,"topicList.html");
                        //对面包屑进行编辑
                        $(parent.document).find(".layui-breadcrumb a:last-child").remove();
                        $(parent.document).find(".layui-breadcrumb a:last-child .layui-box").remove();
                        // window.top.xhTop.closeTabByName(topicDetailName);
                    }
                },	//成功响应的回调
                error: function () {
                    console.log("error");
                }		//失败响应的回调
            });
            layer.close(index);
        }, function(){
        });
    });
    /*点击修改触发事件*/
    $(document).on('click', ".TitleModify", function (event){
        event.stopPropagation();

        //对面包屑进行编辑
        var html='<a data-href="AddTopic.html">编辑题目</a>';
        $(parent.document).find(".layui-breadcrumb a:last-child").append('<span class="layui-box">&gt;</span>');
        $(parent.document).find(".layui-breadcrumb").append(html);

        var topicId=$(this).parent().parent().parent().attr("topicid");
        var topicDetailNameModify=sessionStorage.getItem("topicDetailName")
        openUrl(window.location.href,"AddTopic.html","修改题目");
        if($(this).hasClass("sonTitleModify")){
            sessionStorage.setItem('sonTitleModify',1);
        }
        sessionStorage.setItem('topicId',topicId);
        sessionStorage.setItem('topicDetailNameModify',topicDetailNameModify);
    });
});
var topicSortCancel=$("#topicSortCancel");
$("#topicSortCancel").on("click",function(){
    layer.confirm('取消前是否保存修改？', {
        btn: ['确定','取消'] //按钮
    }, function(index, layero){
        topicSortCancel.css("display", "none");
        topicSortCancel.prev().css("display", "none");
        topicSortCancel.prev().prev().css("display", "inline-block");
        topicSortCancel.prev().prev().prev().css("display", "inline-block");
        $("#TopicManageDetail_popup .popup_title span").css("display", "inline-block");
        $("#TopicManageDetail_popup .popup_body .TitleDetailAll .TitleDetail_content").css("display", "block");
        topicIdListSort();
        layer.close(index);
    }, function(){
        topicSortCancel.css("display", "none");
        topicSortCancel.prev().css("display", "none");
        topicSortCancel.prev().prev().css("display", "inline-block");
        topicSortCancel.prev().prev().prev().css("display", "inline-block");
        $(".addTopic").css("display","block");
        $("#TopicManageDetail_popup .popup_title span").css("display", "inline-block");
        $("#TopicManageDetail_popup .popup_body .TitleDetailAll .TitleDetail_content").css("display", "block");
        var topicGroupId = $("#TitleDetailAll").attr("groupid");
        getGroupAll(topicGroupId);
    });
})
//保存排序
function topicIdListSort(){
    var topicIdList = [];
    for (var i = 0; i < $("#TitleDetailAll li").length; i++) {
        topicIdList.push(parseInt($("#TitleDetailAll li")[i].getAttribute("topicid")));
    }
    var topicGroupId = parseInt($("#TitleDetailAll").attr("groupid"));
    var topicSort = {
        "topicIdList": topicIdList,
        "topicGroupId": topicGroupId,
        //"session": "f62d02686659112a0246f059fd9d4581",
        "timeStamp": User.timeStamp,
        "token": User.token
    };
    topicSort = JSON.stringify(topicSort);
    $.ajax({
        type: 'POST',  //POST/PUT/DELETE/HEAD
        url: Doman.url + Doman.topicSort,
        contentType: "application/json",
        data: topicSort,
        success: function (data) {
            window.location.reload(true);
        },	//成功响应的回调
        error: function () {
            console.log("error");
        }		//失败响应的回调
    });
};
//获取详情页中所有行
function getGroupAll(topicGroupId) {
    var topicDetail = {
        "topicGroupId": topicGroupId,
        "pageSize": 50,
        "page": 0,
        "timeStamp": User.timeStamp,
        "token": User.token
    };
    var topicDetailString = JSON.stringify(topicDetail);
    $.ajax({
        type: 'POST',  //POST/PUT/DELETE/HEAD
        url: Doman.url + Doman.topicDetailList,
        contentType: "application/json",
        data: topicDetailString,
        async: false,
        success: function (data) {
            data = JSON.parse(data).topicList;
            var html='<ul class="TitleDetailAll" id="TitleDetailAll" groupid='+topicDetail.topicGroupId+' count='+data.length+'>';
            for(var i=0;i<data.length;i++){
                if(data[i].topicKind==2){
                    html+=
                    '<li topicid='+data[i].topicId+'>'+
                        '<div class="TitleDetail">'+
                            '<div class="TitleDetail_title">'+
                                '<span class="TitleNo">第<span>'+(i + 1)+'</span>题</span>'+
                                '<span class="TitleType">'+data[i].type+'</span>'+
                                '<span class="TitleAttitude">' + ((data[i].topicType == 1) ? "主观" : "客观") + '</span>'+
                                '<a href="#"  class="btn btn-danger topicRevocation">删除</a>'+
                            '</div>'+
                            '<div class="TitleDetail_content">'+
                                '<div class="question">'+
                                    '<a href="#">'+
                                     '<img src='+data[i].casualWorking+' alt=""/>'+
                                    '</a>'+
                                '</div>'+
                                '<div class="answer">' + ((data[i].topicType == 1) ? '答案:<p><a href="#"><img src='+data[i].answer+' alt=""/> </a></p>' : '答案: <span>'+data[i].answer+'</span>') + '</div>'+
                    ((data[i].eDTOList[0].fileUrl=="")?"":('<div class="video">'+
                                    '<a href='+data[i].eDTOList[0].fileUrl+' class="video_img"></a>'+
                                    '<span>'+data[i].eDTOList[0].fileLength+'"</span>'+
                                '</div>'))+
                    '<div class="detail">' + ((data[i].detail == "" ||data[i].detail == undefined) ? " " : ('<span>详解:</span><br> <a href="#"> <img src='+data[i].detail+' alt=""/> </a>') )+
                    '</div>'+
                            '</div>'+
                        '</div>'+
                     '</li>';
                }else{
                    html+=
                    '<li topicid='+data[i].topicId+'>'+
                        '<div class="TitleDetail">'+
                            '<div class="TitleDetail_title">'+
                                '<span class="TitleNo">第<span>'+(i + 1)+'</span>题</span>'+
                                '<span class="TitleType">'+data[i].type+'</span>'+
                    ((data[i].type==5)?('<span class="btn btn-info addReadingItem">添加小题</span>'):"")+
                                '<a href="#" class="TitleModify">&nbsp;</a>'+
                                '<a href="#"  class="btn btn-danger topicRevocation">删除</a>'+
                    ((data[i].type==5&&data[i].sonWordList.length>1)?('<a href="#" class="btn btn-primary readingSort">排序</a>'+
            '<a href="#" class="btn btn-success readingSortSave">确定</a>'+
            '<a href="#" class="btn btn-info readingSortCancel">取消</a>'):"")+
                            '</div>'+
                            '<div class="TitleDetail_content">'+
                                '<div class="question">'+data[i].topicGetData.content+
                                '</div>'+
                                '<div class="answer">'+ ((data[i].topicGetData.answers == ""||data[i].topicGetData.answers == undefined ) ? " " : ('答案: <span>'+data[i].topicGetData.answers+'</span></div>'))+
                   ((data[i].topicGetData.hearingFile=="")?"":('<div class="video">'+
                                    '<a href='+data[i].topicGetData.hearingFile+' class="video_img"></a>'+
                                    '<span>'+data[i].topicGetData.fileLength+'"</span>'+
                                '</div>'))+
                    '<div class="detail"></div>'+
                            '</div>'+
                            '<div class="sonWordList"></div>'+
                        '</div>'+
                     '</li>';
                }
            }
            html+='</ul>';
            $("#TopicManageDetail .popup_body").html(html);
            TypeName();
            sonWordList(data);
            contentModify();
        },	//成功响应的回调
        error: function () {
            console.log("error");
        }		//失败响应的回调
    });
}

/**
 * 答案和详解样式解析
 * **/
function contentModify(){
    $(".question").each(function(i){
        var content=$(this).html();
        content=content.replace(/\[答案始]/g, "<span class='answerModify'>");
        content=content.replace(/\[\/答案终]/g, "</span>");
        var arr = content.match(/\[详解始](.*?)\[\/详解终]/g);
        var detailSelector=$(this).parent().find(".detail");
        if(arr!=null){
            var html="详解：";
            $.each(arr,function(i,n){
                arr[i]=String(arr[i]).replace(/\[详解始]/g, "");
                arr[i]=String(arr[i]).replace(/\[\/详解终]/g, "");
                html+="<p>"+arr[i]+"</p>";
                detailSelector[0].innerHTML=html;
            });
        }
        content=content.replace(/\[详解始](.*?)\[\/详解终]/g, "");
        $(this).html(content);
    });
}

/**
 * 插入阅读题子题
 * **/
function sonWordList(data){
    data.forEach(function(data,index){
        if(data.sonWordList!=undefined&&data.sonWordList.length!=0){
            var sonWordList = data.sonWordList;
            var readingTitle=index+1;
            var html = "<ul>";
            sonWordList.forEach(function (sonWord, index) {
                html +=
           '<li topicid='+sonWord.topicId+'>'+
                '<div class="TitleDetail">'+
                    '<div class="TitleDetail_title">'+
                        '<span class="TitleNo">'+readingTitle+'-<span>'+(index + 1)+'</span></span>'+
                        '<span class="TitleType">'+sonWord.type+'</span>'+
                        '<a href="#" class="TitleModify sonTitleModify">&nbsp;</a>'+
                        '<a href="#" class="btn btn-danger sonRevocation">删除</a>'+
                    '</div>'+
                    '<div class="TitleDetail_content">'+
                        '<div class="question">'+ sonWord.content+
                        '</div>'+
                        '<div class="answer">' + ((sonWord.answers == "" || sonWord.answers == undefined ) ? " " : ('答案: <span>'+sonWord.answers+'</span></div>'))+
                 ((sonWord.hearingFile == "") ? "" : ('<div class="video">'+
                        '<a href='+sonWord.hearingFile+' class="video_img"></a>'+
                        '<span>'+sonWord.fileLength+'"</span>'+
                    '</div>'))+
                '<div class="detail"></div>'+
                    '</div>'+
                '</div>'+
            '</li>';
            });
            html+="</ul>";
            $("#TitleDetailAll li .sonWordList")[index].innerHTML=html;
            TypeName();
            contentModify();
        }
       //

    });
}

/**改变题目类型名字**/
function TypeName(){
    for (var i = 0; i < $(".TitleType").length; i++) {
        var titleType = $(".TitleType")[i];
        switch (parseInt(titleType.innerHTML)) {
            case 1:
                titleType.innerHTML = "选择题";
                break;
            case 2:
                titleType.innerHTML = "客观填空";
                break;
            case 3:
                titleType.innerHTML = "主观填空";
                break;
            case 4:
                titleType.innerHTML = "简答题";
                break;
            case 5:
                titleType.innerHTML = "阅读题";
                break;
            case 6:
                titleType.innerHTML = "口语训练题";
                break;
            case 7:
                titleType.innerHTML = "解答题";
                break;
            case 8:
                titleType.innerHTML = "选择性填空题";
                break;
            case 9:
                titleType.innerHTML = "判断题";
                break;
            case 10:
                titleType.innerHTML = "多选题";
                break;
            case 11:
                titleType.innerHTML = "听力题";
                break;
            case 12:
                titleType.innerHTML = "英语口语训练";
                break;
            case 13:
                titleType.innerHTML = "语文口语训练";
                break;
            default :
                break;
        }
    }
}

/**
 * 点击删除小题(阅读题)
 * **/
$(document).on("click", ".sonRevocation", function (event) {
    event.stopPropagation();
    var sonWork=$(this).parent().parent().parent();
    var sonWorkId = parseInt(sonWork.attr("topicid"));
    var parentId = parseInt(sonWork.parent().parent().parent().parent().parent().attr("topicid"));
    var sontopicRevocation = {
        "sonWorkId": sonWorkId,
        "parentId": parentId
    };
    sontopicRevocation = JSON.stringify(sontopicRevocation);
    layer.confirm('是否删除', {
        btn: ['确定','取消'] //按钮
    }, function(index, layero){
        $.ajax({
            type: 'POST',  //POST/PUT/DELETE/HEAD
            url: Doman.url + Doman.sontopicRevocation,
            contentType: "application/json",
            data: sontopicRevocation,
            success: function (data) {
                window.location.reload(true);
            },	//成功响应的回调
            error: function () {
                console.log("error");
            }		//失败响应的回调
        });
        layer.close(index);
    }, function(){
    });
    //$("#myModal .reconfirm").on("click", function () {
    //    console.log(sontopicRevocation)
    //    $.ajax({
    //        type: 'POST',  //POST/PUT/DELETE/HEAD
    //        url: Doman.url + Doman.sontopicRevocation,
    //        contentType: "application/json",
    //        data: sontopicRevocation,
    //        success: function (data) {
    //            window.location.reload(true);
    //        },	//成功响应的回调
    //        error: function () {
    //            console.log("error");
    //        }		//失败响应的回调
    //    });
    //});
});

/**点击阅读题排序**/
$(document).on('click', "#TitleDetailAll .TitleDetail_title .readingSort", function (event) {
    event.stopPropagation();
    $("#readingListSort").attr("id","");
    $(this).parent().next().find(".sonWordList ul").attr("id","readingListSort")
    $("#readingListSort .TitleDetail_content").css("display", "none");
    $(this).next().css("display", "inline-block");
    $(this).next().next().css("display", "inline-block");
    $(this).css("display", "none");
    $(this).prev().css("display", "none");
    window.x = new Sortable(readingListSort, {
        group: "words",
        store: {
            get: function (sortable) {
                var order = localStorage.getItem(sortable.options.group);
                return order ? order.split('|') : [];
            },
            set: function (sortable) {
                var order = sortable.toArray();
                order = [];
                localStorage.setItem(sortable.options.group, order.join('|'));
            }
        },
        onEnd: function () {
            var spanArr = $("#readingListSort .TitleDetail .TitleNo span");
            for (var i = 0; i < spanArr.length; i++) {
                spanArr[i].innerHTML = i + 1;
            }
        }
    });
});

/**阅读题排序可保存**/
$(document).on('click', "#TitleDetailAll .TitleDetail_title .readingSortSave", function (event) {
    event.stopPropagation();
    $(this).css("display", "none");
    $(this).next().css("display", "none");
    $(this).prev().css("display", "inline-block");
    $(this).prev().prev().css("display", "inline-block");
    $("#readingListSort .TitleDetail_content").css("display", "block");
    var topicIdList = [];
    for (var i = 0; i < $("#readingListSort li").length; i++) {
        topicIdList.push(parseInt($("#readingListSort li")[i].getAttribute("topicid")));
    }
    var topicGroupId = parseInt($("#TitleDetailAll").attr("groupid"));
    var sontopicSort = {
        "topicIdList": topicIdList,
        "groupid": "0",
        //"session": "f62d02686659112a0246f059fd9d4581",
        "timeStamp": User.timeStamp,
        "token": User.token
    };
    sontopicSort = JSON.stringify(sontopicSort);
    $.ajax({
        type: 'POST',  //POST/PUT/DELETE/HEAD
        url: Doman.url + Doman.sontopicSort,
        contentType: "application/json",
        data: sontopicSort,
        success: function (data) {
            window.location.reload(true);
        },	//成功响应的回调
        error: function () {
            console.log("error");
        }		//失败响应的回调
    });
});
/**取消保存**/
$(document).on('click', "#TitleDetailAll .TitleDetail_title .readingSortCancel", function (event) {
    event.stopPropagation();
    $("#TopicManageDetailCancel .reconfirm").removeClass("reconfirm").addClass("sonReconfirm");
    $("#TopicManageDetailCancel .sonReconfirm").on("click",function(){
        var that=$( "#TitleDetailAll .TitleDetail_title .readingSortSave");
        that.css("display", "none");
        that.next().css("display", "none");
        that.prev().css("display", "inline-block");
        that.prev().prev().css("display", "inline-block");
        $("#readingListSort .TitleDetail_content").css("display", "block");
        var topicIdList = [];
        for (var i = 0; i < $("#readingListSort li").length; i++) {
            topicIdList.push(parseInt($("#readingListSort li")[i].getAttribute("topicid")));
        }
        var topicGroupId = parseInt($("#TitleDetailAll").attr("groupid"));
        var sontopicSort = {
            "topicIdList": topicIdList,
            "groupid": "0",
            //"session": "f62d02686659112a0246f059fd9d4581",
            "timeStamp": User.timeStamp,
            "token": User.token
        };
        sontopicSort = JSON.stringify(sontopicSort);
        $.ajax({
            type: 'POST',  //POST/PUT/DELETE/HEAD
            url: Doman.url + Doman.sontopicSort,
            contentType: "application/json",
            data: sontopicSort,
            success: function (data) {
                window.location.reload(true);
            },	//成功响应的回调
            error: function () {
                console.log("error");
            }		//失败响应的回调
        });
    });
});
